<?php

namespace Xrfg\Api\Trading\Spot\Listeners;

use Xrfg\Api\Trading\Spot\Events\TradeSavedEvent;

class UpdateTicker
{
    protected $redis;

    public function __construct()
    {
        $this->redis = app('redis.connection');
    }

    public function handle(TradeSavedEvent $event)
    {
        $trade = $event->trade;
        $close = $trade->price;
        //更新redis数据
        $key = "etf:ticker:{$trade->symbol}";
        if ($this->redis->exists($key)) {
            $ticker = json_decode($this->redis->get($key), true);
            $ticker['close'] = $close;
            $ticker['number'] += $trade->number;
            $ticker['total'] += $trade->price * $trade->number;
            $ticker['low'] = $ticker['low'] > $trade->price ? $trade->price : $ticker['low'];
            $ticker['high'] = $ticker['high'] < $trade->price ? $trade->price : $ticker['high'];
        } else {
            $ticker = [
                'close' => $close,
                'open' => $close,
                'high' => $close,
                'low' => $close,
                'number' => $trade->number,
                'total' => $trade->price * $trade->number,
            ];
        }
        $this->redis->set($key, json_encode($ticker));
    }
}
